package com.dhcc.DRGsHosp.infra.util;

import com.dhcc.DRGsHosp.core.domain.IndexCal;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import org.apache.commons.beanutils.PropertyUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.openkoala.security.facade.SecurityAccessFacade;
import org.openkoala.security.shiro.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Clob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * @ClassName: DrgsIndex  
 * @Description ：    新指标计算方法支持
 * @Date: 2017年5月23日 上午11:17:08  
 * @Author LiuHongJun 
 * @Version 2.5.0 DHC-DRGs
 */
public class DrgsIndex{
	private static final Logger logger = LoggerFactory.getLogger(DrgsIndex.class);
	private static SecurityAccessFacade securityAccessFacade;
    //这个类不能实例化
    private DrgsIndex(){
    }
	private static EntityRepository getRepository() {
		EntityRepository repository = null;
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
	
	/**
	 * 
	 *  formateDateFrom.  
	 *  @Description：
	 *  @Author LiuHongjun
	 *  @param dateFrom 开始时间
	 *  @return 返回格式化时间字符串
	 *  @Date:2017年5月19日上午10:47:06
	 */
	public static String formateDateFrom(String dateFrom) {
			if (dateFrom!=null  &&dateFrom.length() < 10 && dateFrom.length() > 6) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Calendar c = Calendar.getInstance();
				String year = dateFrom.substring(0, 4);
				String month = dateFrom.substring(5, 7);
				c.set(Integer.parseInt(year), Integer.parseInt(month) - 1, 1);
				String now = null;
				try {
					c.add(Calendar.DATE, 0);
					now = format.format(c.getTime());
				} catch (Exception e) {
					e.printStackTrace();
				}
				return now;
			} else if (dateFrom!=null &&dateFrom.length() == 10) {
				return dateFrom;
			} else if (dateFrom!=null &&dateFrom.length() == 4) {
				return dateFrom + "-01-01";
			} else if (dateFrom!=null && dateFrom.length() > 10) {
				return dateFrom;
			} else {
				return now();//其他情况返回系统时间
			}
	}
	/**
	 * 
	 *  now.  
	 *  @Description：获取系统时间
	 *  @Author LiuHongjun
	 *  @return 
	 *  @Date:2017年7月18日下午5:25:59
	 */
	private static String now()
	{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		   String now = format.format(new Date());
		   return now;
	}
	/**
	 * 
	 *  formateDateTo.  
	 *  @Description：
	 *  @Author LiuHongjun
	 *  @param dateTo结束时间
	 *  @return 返回格式化时间字符串
	 *  @Date:2017年5月19日上午10:47:39
	 */
	public static String formateDateTo(String dateTo) {
		SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
			if (dateTo!=null&&dateTo.length() < 10 && dateTo.length() > 6) {
				String year = dateTo.substring(0, 4);
				String month = dateTo.substring(5, 7);
				c.set(Integer.parseInt(year), Integer.parseInt(month) - 1, 1);
				String now = null;
				try {
				    c.set(Calendar.DATE, 1);
		            c.add(Calendar.MONTH, 1); 
		            c.add(Calendar.DATE, -1); 
					now = formato.format(c.getTime());
				} catch (Exception e) {
					e.printStackTrace();
				}
				return now;
			} else if (dateTo!=null&&dateTo.length() == 10) {
				String year = dateTo.substring(0, 4);
				String month = dateTo.substring(5, 7);
				String day = dateTo.substring(8, 10);
			    c.set(Calendar.DATE, 1);
	            c.add(Calendar.MONTH, 1); 
	            c.add(Calendar.DATE, -1); 
				c.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
				return formato.format(c.getTime());
			} else if (dateTo!=null&&dateTo.length() == 4) {
				String year = dateTo.substring(0, 4);
				c.set(Integer.parseInt(year), 11, 1);
				 c.set(Calendar.DATE, 1);
		         c.add(Calendar.MONTH, 1); 
		         c.add(Calendar.DATE, -1); 
				return formato.format(c.getTime());
			} else if (dateTo!=null&&dateTo.length() > 10) {
				return dateTo;
			} else {
				return now();//其他情况返回系统时间
			}
	}

	/**
	 *
	 *  getDateFromCc.
	 *  @Description：同比 year 环比：month 绩效比  ：manager标杆比：std 院内均值 hosp
	 *  @Author LiuHongjun
	 *  @param dateFrom
	 *  @param compartype
	 *  @return
	 *  @Date:2017年5月20日上午11:29:51
	 */
	public static String getDateFromCc(String date,String compartype) {
		String mrDate="";
		if(StringUtils.hasLength(date)&&"year".equals(compartype)){
			mrDate = newDate(date, -12);
		}else if(StringUtils.hasLength(date)&&"quarter".equals(compartype)){
			mrDate = newDate(date, -3);
		}else if(StringUtils.hasLength(date)&&"month".equals(compartype)){
			mrDate = newDate(date, -1);
		}else if("std".equals(compartype)||"manage".equals(compartype)||"hosp".equals(compartype)){
			mrDate=date;
		}
		return mrDate;
	}
	/**
	 *  getDateToCc.
	 *  @Description：
	 *  @Author LiuHongjun
	 *  @param dateTo
	 * @param compartype  同比 year 环比：month 绩效比  ：manager标杆比：std 院内均值 hosp_avg
	 *  @return
	 *  @Date:2017年5月20日上午11:23:55
	 */
	public static String getDateToCc(String date, String compartype) {
		String mrDate="";
		if(StringUtils.hasLength(date)&&"year".equals(compartype)){
			mrDate = newDate(date, -12);
		}else if(StringUtils.hasLength(date)&&"month".equals(compartype)){
			mrDate = newDate(date, -1);
		}else if("std".equals(compartype)||"manage".equals(compartype)||"hosp".equals(compartype)){
			mrDate=date;
		}
		return mrDate;
	}

	/**
	 * 
	 *  newDate.  
	 *  @Description：根据日期返回一个新的日期格式
	 *  @Author LiuHongjun
	 *  @param date
	 *  @param m
	 *  @return 
	 *  @Date:2017年5月20日上午11:50:47
	 */
	public static String newDate(String date, int m){
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			if(date.length()<8){
				format = new SimpleDateFormat("yyyy-MM");
			}
			Calendar c = Calendar.getInstance(); 
			Date d = format.parse(date);  
			c.setTime(d);
			try {
				if(isLastDayOfMonth(date)){
					//月底,直接过去上m个月最后一天
					c.add(Calendar.MONTH, m+1);
					c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), 0);
				} else{
					c.add(Calendar.MONTH, m);
				}
			} catch (Exception e) {
				c.add(Calendar.MONTH, m);
			} 		
			String now = format.format(c.getTime());
		    return now;
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return date;
	}
	/**
	 * 
	 *  isLastDayOfMonth.  
	 *  @Description：判定一个日期为月末最后一天
	 *  @Author LiuHongjun
	 *  @param date
	 *  @return
	 *  @throws ParseException 
	 *  @Date:2017年5月20日上午11:53:22
	 */
	public static boolean isLastDayOfMonth(String date) throws ParseException { 
		Date d = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        Calendar calendar = Calendar.getInstance(); 
        calendar.setTime(d); 
        calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1)); 
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) { 
            return true; 
        } 
        return false; 
    }
	
	/**
	 * 
	 *  jointListMap.  
	 *  @Description：拼接两个list
	 *  @Author LiuHongjun
	 *  @param listold
	 *  @param listnew
	 *  @return 
	 *  @Date:2017年5月20日下午4:36:03
	 */
	public static List<Map<String, Object>> jointListMapCc(List<Map<String, Object>> listold, List<Map<String, Object>> listnew){
    	int i=0;
    	int j=0;
    	int iMax=listold.size();
    	int jMax=listnew.size();
    	if(iMax==0 || jMax==0) return listold;
		for(i=0; i<iMax; i++){
    		int k=j;
    		Map<String, Object> map = listold.get(i);
    		String ccode1 = map.get("ccode")!=null?map.get("ccode").toString():"";
    		while(true){
    			if(k==jMax) break;
    			Map<String, Object> mapcc = listnew.get(k);
        		String ccode2 = mapcc.get("ccode")!=null?mapcc.get("ccode").toString():"";
    			if(ccode2.equals(ccode1)){
    				 for(String dataKey : mapcc.keySet())   {    
    					 map.put(dataKey+"cc", mapcc.get(dataKey));
    				 } 
    				 j++;
    				 break;
    			}
    			k++;
    		}
    	}
    	return listold;
    }
	/**
	 * 
	 *  jointListMap.  
	 *  @Description：
	 *  @Author LiuHongjun
	 *  @param listold
	 *  @param listnew
	 *  @return 
	 *  @Date:2017年5月22日上午11:49:49
	 */
	public static List<Map<String, Object>> jointListMap(List<Map<String, Object>> listold, List<Map<String, Object>> listnew){
    	int i=0;
    	int j=0;
    	int iMax=listold.size();
    	int jMax=listnew.size();
    	if(iMax==0 || jMax==0) return listold;
		for(i=0; i<iMax; i++){
    		int k=j;
    		Map<String, Object> map = listold.get(i);
    		String ccode1 = map.get("ccode")!=null?map.get("ccode").toString():"";
    		while(true){
    			if(k==jMax) break;
    			Map<String, Object> mapcc = listnew.get(k);
        		String ccode2 = mapcc.get("ccode")!=null?mapcc.get("ccode").toString():"";
    			if(ccode2.equals(ccode1)){
    				 for(String dataKey : mapcc.keySet())   {    
    					 map.put(dataKey, mapcc.get(dataKey));
    				 } 
    				 j++;
    				 break;
    			}
    			k++;
    		}
    	}
    	return listold;
    }
	/**
	 * 
	 *  mapListClinic.  
	 *  @Description：合并关于主诊组的数据
	 *  @Author LiuHongjun
	 *  @param listold
	 *  @param listnew
	 *  @return 
	 *  @Date:2017年5月22日上午11:50:39
	 */
	public static List<Map<String, Object>> jointListMapClinic(List<Map<String, Object>> listold, List<Map<String, Object>> listnew){
    	int i=0;
    	int iMax=listold.size();
    	int jMax=listnew.size();
    	if(iMax==0 || jMax==0) return listold;
    	if(iMax>0 && jMax>0 ){
    		Map<String,Object> map2 = listnew.get(0);
    		for(i=0; i<iMax;i++){
    			Map<String,Object> map1 = listold.get(i);
    			for(String dataKey : map2.keySet()){
    				map1.put(dataKey+"cc",map2.get(dataKey));
    			}
    		}
    	}
    	return listold;
    }
	
	/**
	 *  结果拼接 将list数据拼到map里
	 *  mergeMapList.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @param mapBase 
	 *  @param listnew 需要添加的list
	 *  @param filed  拼接字段
	 *  @return 
	 *  @Date:2017年12月13日下午9:15:45
	 */
	public static Map<String,Map<String,Object>> mergeMapList(Map<String,Map<String,Object>> mapBase, List<Map<String, Object>> listnew,String filed){
		// 遍历新List将结果放至原map中
		for(Map<String,Object> map : listnew) {
			if(mapBase.get(map.get(filed)) != null){
				mapBase.get(map.get(filed)).putAll(map);
			}
		}
		return mapBase;
	}
	
	/**
	 * 
	 *  ClobToString.  
	 *  @Description：oracle.sql.Clob类型转换成String类型
	 *  @Author LiuHongjun
	 *  @param clob
	 *  @return
	 *  @throws Exception 
	 *  @Date:2017年5月23日上午11:16:17
	 */
	public static String ClobToString(Clob clob) throws Exception {
		String reString = "";
		Reader is = clob.getCharacterStream();// 得到流
		BufferedReader br = new BufferedReader(is);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
			sb.append(s);
			sb.append(" \n ");
			s = br.readLine();
		}
		reString = sb.toString();
		return reString;
	}
	/**
	 *  @desp  ：标杆比中根据比较类型修改sql（计算标杆，病组标杆，外院标杆）
	 *  @Author： liuhongjun
	 *  @param index
	 *  @Date  :2018年3月13日上午11:52:44
	 */
	public static void replaceStdSqlByMscode(IndexCal index,String quotaCode,String quotaType,String stdQuota){
		String sql=index.getSqlStr();
		String msCode=index.getMsCode();
		String managerdtl="";//外院标杆
		String managerStd="";//病组管理目标
		String stdManager="";//年度标杆
		if("RATIO".equals(quotaType)){//当指标类型为比率类的，目前有三个指标：耗占比，药占比，药耗占比，在查询时，需另外查询次均费用的标杆
			sql=sql.replaceAll("-stdobj-", ",ma.AvgFee");
			managerdtl="SELECT dt.pardrg_code as drgCode ,\n" + 
					"sum((case when dt.parquota_code=:quotaCode then dt.manage_benchmark else 0 end)) stdValue, \n" + 
					"sum((case when dt.parquota_code='AvgFee' then dt.manage_benchmark else 0 end)) AvgFee \n" + 
					"FROM drgs.t_managesummarydtl dt  \n" + 
					"where dt.par_ms_code=:ms_code  \n" + 
					"and (dt.parquota_code=:quotaCode or dt.parquota_code='AvgFee') \n" + 
					"and dt.std_year=:stdYear  \n" +
					"group by dt.pardrg_code";
			
			managerStd="SELECT dt.as_drg_code as drgCode, \n" +
					" stdQuotaCode as stdValue, \n" + 
					" AS_AVG_FEE as AvgFee \n" + 
					"FROM DRGS.t_Annualstd dt \n" + 
					"where dt.as_id=:stdId \n";
			
			stdManager=" SELECT dt.pardrg_code as drgCode ,\r\n" + 
					"sum((case when dt.parquota_code=:quotaCode then dt.manage_benchmark else 0 end)) stdValue, \n" + 
					"sum((case when dt.parquota_code='AvgFee' then dt.manage_benchmark else 0 end)) AvgFee \n" + 
					"    FROM drgs.t_quotamanage dt \r\n" + 
					"    where dt.par_ms_code='manager_inner' \r\n" + 
					"    and dt.pardep_code is null\r\n" + 
					"    and dt.pardepgroup_code is null\r\n" + 
					"    and dt.pardrg_code is not null\r\n" + 
					"    and dt.manage_year=:manageYear \r\n" + 
					"    and (dt.parquota_code=:quotaCode or dt.parquota_code='AvgFee') \n" +
					"    group by dt.pardrg_code";
		}else{//当指标类型不是比率类的，如次均费用、平均住院日等
			sql=sql.replaceAll("-stdobj-", "");
			managerdtl="SELECT dt.pardrg_code as drgCode ,\n" + 
					"dt.manage_benchmark   AS stdValue \n" + 
					"FROM drgs.t_managesummarydtl dt  \n" + 
					"where dt.par_ms_code=:ms_code  \n" + 
					"and dt.parquota_code=:quotaCode  \n" + 
					"and dt.std_year=:stdYear  \n" ;
			
			managerStd="SELECT dt.as_drg_code as drgCode, \n"
					+ " stdQuotaCode as stdValue \n" + 
					"FROM DRGS.t_Annualstd dt \n" + 
					"where dt.as_id=:stdId \n";
			
			stdManager=" SELECT dt.pardrg_code as drgCode ,\r\n" + 
					"    dt.manage_benchmark   AS stdValue \r\n" + 
					"    FROM drgs.t_quotamanage dt \r\n" + 
					"    where dt.par_ms_code='manager_inner' \r\n" + 
					"    and dt.pardep_code is null\r\n" + 
					"    and dt.pardepgroup_code is null\r\n" + 
					"    and dt.pardrg_code is not null\r\n" + 
					"    and dt.manage_year=:manageYear \r\n" + 
					"    and dt.parquota_code=:quotaCode ";
		}
		if(sql.contains("-replace_compareobj-")) {
			//计算标杆
			if("std_computer".equals(msCode)&&StringUtils.hasLength(stdQuota)) {
				sql=sql.replaceAll("-replace_compareobj-", managerStd);
				sql=sql.replaceAll("stdQuotaCode", stdQuota);
			//病组标杆
			}else if("std_manager".equals(msCode)) {
				sql=sql.replaceAll("-replace_compareobj-", stdManager);
			//外院标杆
			}else {
				sql=sql.replaceAll("-replace_compareobj-", managerdtl);
			}
		}
		if(sql.contains("-replace_calculationobj-")){
			if("RATIO".equals(quotaType)){//当指标类型为比率类的，目前有三个指标：耗占比，药占比，药耗占比
				sql=sql.replaceAll("-replace_calculationobj-", "100*sum(stdValue*AvgFee*cnt/100)/sum(AvgFee*cnt)");
			}else if("AVG".equals(quotaType)){//当指标类型为求平均值类的，目前指标有：平均住院日，次均费用，次均药品费用，次均耗材费用
				sql=sql.replaceAll("-replace_calculationobj-", "sum(stdValue*cnt)/sum(cnt)");
			}else if("TOTAL".equals(quotaType)){//当指标类型为求总费用类的，目前指标有：住院总费用，药品总费用，耗材总费用
				sql=sql.replaceAll("-replace_calculationobj-", "sum(stdValue*cnt)");
			}else if("DEADRATIO".equals(quotaType)){//当指标类型为死亡率
				sql=sql.replaceAll("-replace_calculationobj-", "100*ceil(sum(stdValue*cnt/100))/sum(cnt)");
			}else if("DEADCASECNT".equals(quotaType)){//当指标类型为死亡人数
				sql=sql.replaceAll("-replace_calculationobj-", "ceil(sum(stdValue*cnt/100))");
			}
		}
		index.setSqlStr(sql);
	}
	/**
	 *  @desp  ：将系统指标代码映射为年度标杆表中的字段
	 *  @Author： liuhongjun
	 *  @return
	 *  @Date  :2018年3月13日下午2:03:05
	 */
	public static Map<String, String> quotaCodeToStdCode(){	
		Map<String, String> map=new HashMap<>();
		map.put("InCaseCnt", "AS_TOTAL_CASE");
		map.put("AvgFee", "AS_AVG_FEE");
		map.put("AvgDays", "AS_AVG_DAYS");
		map.put("DeadCaseCnt", "AS_DEAD_CNT");
		map.put("TotalWeight", "AS_WEIGHT");
		map.put("RiskLevel", "AS_RISK_LEVEL");
		map.put("DrugRatio", "AS_DRUG_RATIO");
		map.put("AvgDrugFee", "AS_AVG_DRUG_FEE");
		map.put("AvgMateFee", "AS_AVG_MATERIAL_FEE");
		map.put("MedFee", "AS_DRG_MED_COST");
		map.put("NursFee", "AS_DRG_NURS_COST");
		map.put("TechFee", "AS_DRG_TECH_COST");
		map.put("DrugMaterFee", "AS_DRG_DRUG_COST");
		map.put("ManageFee", "AS_DRG_MANAGE_COST");
		map.put("AvgDrugMateFee", "AS_DRG_DRUG_COST");
		return map;
	}
	/**
	 * 
	 *  replaceSqlByMonitorType.  
	 *  @Description：根据分析的对象替换用来groupby orderby的字段 
	 *  @Author LiuHongjun
	 *  @param index
	 *  @param sqlStr 
	*  @param  1=1基本过滤条件，其他指标都不用,4=4是特异病例专用替换
	 *  @Date:2017年5月23日上午11:46:54
	 */
	public static void replaceSqlByMonitorType(IndexCal index,String quotaCode){
		String sqlStr=index.getSqlStr();
//		String quotaCode=index.getQuotaCode();
		if("depGroup".equals(index.getMonitorType())){
			//替换医师
			sqlStr=replaceDoctor( sqlStr, index);
			
			String deps = index.getDeps();
			//多科室的情况
			if(StringUtils.hasLength(deps)){//多科室的 此处主要是求多科室汇总的情况
				sqlStr = sqlStr.replaceAll("-obj-", "'deps' ccode");
				sqlStr = sqlStr.replaceAll("-obj1-", "'多科室' ddesc, 'deps' ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj-", "''");
				sqlStr = sqlStr.replaceAll("-grbyobj1-", "'', ''");
				sqlStr = sqlStr.replaceAll("-obj2-", "'deps' ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj2-", "''");
				sqlStr = sqlStr.replaceAll("1=1", " depgroup.DEPGROUP_CODE is not null and  1=1 ");

			}else {//正常的  特定科室组分组条件替换
				sqlStr = sqlStr.replaceAll("-obj-", "depgroup.DEPGROUP_CODE ccode");
				sqlStr = sqlStr.replaceAll("-obj1-", "depgroup.DEPGROUP_DESC ddesc, depgroup.DEPGROUP_CODE ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj-", "depgroup.DEPGROUP_CODE");
				sqlStr = sqlStr.replaceAll("-grbyobj1-", "depgroup.DEPGROUP_DESC, depgroup.DEPGROUP_CODE");
				sqlStr = sqlStr.replaceAll("-obj2-", "depgroup.DEPGROUP_CODE ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj2-", "depgroup.DEPGROUP_CODE");
				sqlStr = sqlStr.replaceAll("1=1", " depgroup.DEPGROUP_CODE is not null and  1=1 ");
			}
			sqlStr = sqlStr.replaceAll("-baseobj1-", "depgroup.DEPGROUP_DESC ddesc, depgroup.DEPGROUP_CODE ccode,depgroup.DEPGROUP_ORDER drgorder");
			sqlStr = sqlStr.replaceAll("-grbybaseobj1-", "depgroup.DEPGROUP_DESC, depgroup.DEPGROUP_CODE,depgroup.DEPGROUP_ORDER");
			
		}else if("dep".equals(index.getMonitorType())){
			
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			//分组历史表替换（针对历史数据查询）
			if("1".equals(index.getIsHistory())) {
				sqlStr = sqlStr.replaceAll("t_patientdrg", "t_patientdrg_h");
			}
			sqlStr = sqlStr.replaceAll("-obj-", "dep.DEP_CODE ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "dep.DEP_NAME ddesc, dep.DEP_CODE ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj-", "dep.DEP_CODE");
			sqlStr = sqlStr.replaceAll("-grbyobj1-", "dep.DEP_NAME, dep.DEP_CODE");
			sqlStr = sqlStr.replaceAll("-obj2-", "dep.DEP_CODE ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj2-", "dep.DEP_CODE");
			sqlStr = sqlStr.replaceAll("1=1", " dep.DEP_CODE is not null and  1=1 ");
			
			sqlStr = sqlStr.replaceAll("-baseobj1-", "dep.DEP_NAME ddesc, dep.DEP_CODE ccode,dep.DEP_ORDER drgorder");
			sqlStr = sqlStr.replaceAll("-grbybaseobj1-", "dep.DEP_NAME, dep.DEP_CODE,dep.DEP_ORDER");
			
		}else if("ward".equals(index.getMonitorType())){
			//医师表没用的时候去掉
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			
			sqlStr = sqlStr.replaceAll("-obj-", "ward.ward_code ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "ward.ward_code ccode, ward.ward_desc ddesc");
			sqlStr = sqlStr.replaceAll("-grbyobj-", "ward.ward_code");
			sqlStr = sqlStr.replaceAll("-grbyobj1-", "ward.ward_code, ward.ward_desc");
			sqlStr = sqlStr.replaceAll("-obj2-", "'1' ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
			sqlStr = sqlStr.replaceAll("1=1", " ward.ward_code is not null and  1=1 ");
			
			sqlStr = sqlStr.replaceAll("-baseobj1-", "ward.ward_code ccode, ward.ward_desc ddesc,ward.WARD_ORDER drgorder");
			sqlStr = sqlStr.replaceAll("-grbybaseobj1-", "ward.ward_code , ward.ward_desc ,ward.WARD_ORDER");
			
		}else if("clinic".equals(index.getMonitorType())){
			//主诊组替换
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);

		}else if("protomedicus".equals(index.getMonitorType())){
			//主任医师
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
		}else if("physician".equals(index.getMonitorType())){
			//住治医师
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			
		}else if("resident".equals(index.getMonitorType())){
			//住院医师
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
		}else if("mdc".equals(index.getMonitorType())){
			sqlStr=replaceBaseQuotaCodeByMonitiorType( sqlStr, quotaCode);
			sqlStr=replaceBaseObjtorealObj(sqlStr);
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			sqlStr = sqlStr.replaceAll("-obj-", "mdc.MDC_CODE ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "MDC_DESC ddesc, mdc.MDC_CODE ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj-", "mdc.MDC_CODE");
			sqlStr = sqlStr.replaceAll("-grbyobj1-", "MDC_DESC, mdc.MDC_CODE");
			sqlStr = sqlStr.replaceAll("-obj2-", "'1' ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
		}else if("adrg".equals(index.getMonitorType())){
			sqlStr=replaceBaseQuotaCodeByMonitiorType( sqlStr, quotaCode);
			sqlStr=replaceBaseObjtorealObj(sqlStr);
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);			
			sqlStr = sqlStr.replaceAll("-obj-", "adrg.ADRG_CODE ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "ADRG_DESC ddesc, adrg.ADRG_CODE ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj-", "adrg.ADRG_CODE");
			sqlStr = sqlStr.replaceAll("-grbyobj1-", "ADRG_DESC, adrg.ADRG_CODE");
			sqlStr = sqlStr.replaceAll("-obj2-", "'1' ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
		}else if("drgs".equals(index.getMonitorType())){
			sqlStr=replaceBaseQuotaCodeByMonitiorType( sqlStr, quotaCode);
			sqlStr=replaceBaseObjtorealObj(sqlStr);
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			
			sqlStr = sqlStr.replaceAll("-obj-", "drg.drg_code ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "nvl(drg_desc, '未入组') ddesc, nvl(drg.drg_code, '未入组') ccode");
			sqlStr = sqlStr.replaceAll("-obj1-", "drg_desc ddesc, drg.drg_code ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj-", "drg.drg_code");
			sqlStr = sqlStr.replaceAll("-grbyobj1-", "drg_desc, drg.drg_code");
			if("1".equals(index.getType3())){
				sqlStr = sqlStr.replaceAll("1=1", " drg.drg_code is not null and  1=1 ");
			}
			sqlStr = sqlStr.replaceAll("-obj2-", "'1' ccode");
			sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
		}else{
			sqlStr=replaceBaseObjtorealObj(sqlStr);
			//替换医师
			sqlStr = replaceDoctor( sqlStr, index);
			
			if(StringUtils.hasLength(index.getIsHistory())&&"1".equals(index.getIsHistory())) {
				sqlStr = sqlStr.replaceAll("t_patientdrg", "t_patientdrg_h");
			}
			//全院按时间按查询数据（测试阶段，不设置groupByTime不走）
			if(StringUtils.hasLength(index.getGroupByTime())&&"1".equals(index.getGroupByTime())){
				if("MC".equals(index.getMrType())){
					sqlStr = sqlStr.replaceAll("-obj-", "to_char(ipinfo.P00290000,'yyyy') ccode");
					sqlStr = sqlStr.replaceAll("-grbyobj-", "to_char(ipinfo.P00290000,'yyyy')");
					sqlStr = sqlStr.replaceAll("-obj1-", " to_char(ipinfo.P00290000,'yyyy') ddesc, to_char(ipinfo.P00290000,'yyyy') ccode");
					sqlStr = sqlStr.replaceAll("-grbyobj1-", "to_char(ipinfo.P00290000,'yyyy'), to_char(ipinfo.P00290000,'yyyy')");
					sqlStr = sqlStr.replaceAll("-obj2-", "to_char(ipinfo.P00290000,'yyyy')  ccode");
					sqlStr = sqlStr.replaceAll("-grbyobj2-", " to_char(ipinfo.P00290000,'yyyy') ");
				}
				
			}else{
				sqlStr = sqlStr.replaceAll("-obj-", "1 ccode");
				sqlStr = sqlStr.replaceAll("-obj1-", "'全院' ddesc, 1 ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj-", "1");
				sqlStr = sqlStr.replaceAll("-grbyobj1-", "'全院', 1");
				sqlStr = sqlStr.replaceAll("-obj2-", "'1' ccode");
				sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
			}
		}	
		//借用type1字段过滤科室理论drg
		if("1".equals(index.getType1())){
			sqlStr = sqlStr.replaceAll("on ipinfo.P00300001=dep.dep_code", "  on ipinfo.P00300001=dep.dep_code	 \n left join DRGs.t_Departmentdrg depdrg	\n on depdrg.pardep_code=dep.dep_code and 	depdrg.pardrg_code=drg.drg_code and depdrg.version=drg.ver_code  \n");
			sqlStr = sqlStr.replaceAll(" 1=1 ", " depdrg.id is not null and  1=1  ");
		}else if("0".equals(index.getType1())){
			sqlStr = sqlStr.replaceAll("on ipinfo.P00300001=dep.dep_code", "  on ipinfo.P00300001=dep.dep_code	 \n left join DRGs.t_Departmentdrg depdrg	\n on depdrg.pardep_code=dep.dep_code and 	depdrg.pardrg_code=drg.drg_code and depdrg.version=drg.ver_code  \n");
			sqlStr = sqlStr.replaceAll(" 1=1 ", " depdrg.id is null and  1=1  ");
		}
		index.setSqlStr(sqlStr);
	}
	/**
	 *  @Discription：base 指标在病组这条线上需要过滤未入组的病例
	 *  @Author： liuhongjun
	 *  @param sqlStr
	 *  @param quotaCode
	 *  @return
	 *  @Date:2018年4月16日下午2:50:51
	 */
	private static String replaceBaseQuotaCodeByMonitiorType(String sqlStr,String quotaCode) {
		if("Base".equals(quotaCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "  b.pardrg_code is not null and 1=1  ");
		}
		return sqlStr;
	}
	/**
	 *  @desp  ：对于不排序的base将里面的替换符号换掉
	 *  @Author： lhj
	 *  @param sqlStr
	 *  @return
	 *  @Date  :2018年1月30日下午5:07:06
	 */
	private static String replaceBaseObjtorealObj(String sqlStr) {
		sqlStr = sqlStr.replaceAll("-baseobj1-", "-obj1-") ;
		sqlStr = sqlStr.replaceAll("-grbybaseobj1-", "-grbyobj1-") ;
		sqlStr = sqlStr.replaceAll(",drgorder", " ") ;	
		sqlStr = sqlStr.replaceAll("order by drgorder", "order by ccode") ;	
		
		return sqlStr;
	}
	/**
	 * 
	 *  createSearch.  
	 *  @Description：拼接查询条件
	 *  @Author LiuHongjun
	 *  @param index 
	 *  @param  1=1基本过滤条件，其他指标都不用,4=4是特异病例专用替换
	 *  @Date:2017年6月6日下午7:33:15
	 */
	public static void createSearch(IndexCal index, Map<String, Object> map) {
		String deps = index.getDeps();
		String mdcs = index.getMdcs();
		String depGroupCode = index.getPardepgroupCode();
		String depCode = index.getPardepCode();
		String clinicName = index.getPargroupName();
		String protomedicus = index.getProtomedicus();
		String wardCode = index.getParwardCode();
		String mdcCode = index.getParmdcCode();
		String adrgCode = index.getParadrgCode();
		String drgCode = index.getPardrgCode();
		String physician = index.getPhysician();
		String resident = index.getResident();
		String isHistory = index.getIsHistory();
		String verCode = index.getVerCode();
		String pType = index.getpType();
		String sqlStr = index.getSqlStr();
		String isKeyDisGroup = index.getIsKeyDisGroup();
		String isDifDisGroup = index.getIsDifDisGroup();//是否疑难病组
		String isPayGroup = index.getIsPayGroup();
		String groupType = index.getGroupType();
		String specHeade = index.getSpecHeader();// 指定特异病例的上一级
		String hospCode = index.getHospCode();// 院区编码
		String monitorType= index.getMonitorType();
		String userAccount = index.getUserCode();
		String roleName = index.getRoleName();
		String hospName = "";
		hospName = GlobalData.hospName;
		// 组装sql查询条件部分
		// ***科室组*****
		if (StringUtils.hasLength(depGroupCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   depgroup.DEPGROUP_CODE=:depGroupCode and  1=1   ");
			sqlStr = sqlStr.replaceAll("9=9", "   depgroup.DEPGROUP_CODE=:depGroupCode and  9=9");// 每床日权重
			//本层次的时候不拼接，因为是获取的上一级
			if(!"depGroup".equals(monitorType)) {
				sqlStr = sqlStr.replaceAll("'capScore'='capScore'", "  depgroup.DEPGROUP_CODE=:depGroupCode and  'capScore'='capScore' ");// 科室安全得分
			}
			map.put("depGroupCode", depGroupCode);
		}
		// ***科室*****
		if (StringUtils.hasLength(depCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "  dep.DEP_CODE=:depCode and  1=1  ");
			sqlStr = sqlStr.replaceAll("9=9", "  dep.DEP_CODE=:depCode  and  9=9 ");// 每床日权重
			//本层次的时候不拼接，因为是获取的上一级
			if(!"dep".equals(monitorType)) {
				sqlStr = sqlStr.replaceAll("'capScore'='capScore'", "  dep.DEP_CODE=:depCode and  'capScore'='capScore' ");// 科室安全得分	
			}
			map.put("depCode", depCode);
		}
		// ***病区*****
		if (StringUtils.hasLength(wardCode)) { // 病区
			sqlStr = sqlStr.replaceAll("1=1", "   ward.ward_code=:wardCode and  1=1  ");
			//本层次的时候不拼接，因为是获取的上一级
			if(!"ward".equals(monitorType)) {
				sqlStr = sqlStr.replaceAll("'capScore'='capScore'", "  ward.ward_code=:wardCode and  'capScore'='capScore' ");// 安全得分
			}
			map.put("wardCode", wardCode);
		}
		/*************************** 以下医师均传递医师编码 *************************************/
		// ***主诊组*****
		if (StringUtils.hasLength(clinicName) && !"null".equals(clinicName)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00601001=:clinicName and  1=1 ");
			map.put("clinicName", clinicName);
		} else if ("null".equals(clinicName)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00601001 is null and  1=1 ");
		}
		// ***主任医师*****
		if (StringUtils.hasLength(protomedicus) && !"null".equals(protomedicus)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00600201=:protomedicus and  1=1   ");
			map.put("protomedicus", protomedicus);
		} else if ("null".equals(protomedicus)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00600201 is null and  1=1   ");
		}
		// ***主治医师*****
		if (StringUtils.hasLength(physician) && !"null".equals(physician)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00600301=:physician and  1=1   ");
			map.put("physician", physician);
		} else if ("null".equals(physician)) {
			sqlStr = sqlStr.replaceAll("1=1", "   ipinfo.P00600301 is null and  1=1   ");
		}
		// ***住院医师*****
		if (StringUtils.hasLength(resident) && !"null".equals(resident)) {
			sqlStr = sqlStr.replaceAll("1=1", "    ipinfo.P00600401=:resident and  1=1    ");
			map.put("resident", resident);
		} else if ("null".equals(resident)) {
			sqlStr = sqlStr.replaceAll("1=1", "    ipinfo.P00600401 is null and  1=1   ");
		}
		// ***MDC*****
		if (StringUtils.hasLength(mdcCode) && !"null".equals(mdcCode) && !"未入组".equals(mdcCode) && !"未分组".equals(mdcCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   mdc.MDC_CODE=:mdcCode and  1=1   ");
			map.put("mdcCode", mdcCode);
		} else if (StringUtils.hasLength(mdcs) && !"null".equals(mdcs) && !"未入组".equals(mdcs) && !"未分组".equals(mdcCode)) {
			// ***多个MDC*****
			String[] mdcList = mdcs.split(",");
			String mdcSql = "   ( ";
			for (int i = 0; i < mdcList.length; i++) {
				String mdcListNow = mdcList[i];
				if (i == mdcList.length - 1) {
					mdcSql += " mdc.MDC_CODE = '" + mdcListNow + "' ";
				} else {
					mdcSql += " mdc.MDC_CODE = '" + mdcListNow + "' or ";
				}
			}
			mdcSql += " ) and 1=1  ";
			sqlStr = sqlStr.replaceAll("1=1", mdcSql);
		} else if ("null".equals(mdcCode) || "未入组".equals(mdcCode) || "未分组".equals(mdcCode) || StringUtils.hasLength(mdcs) && !"null".equals(mdcs) && !"未入组".equals(mdcs) && !"未分组".equals(mdcCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   mdc.MDC_CODE is null and  1=1   ");
		}

		// ***ADRG*****
		if (StringUtils.hasLength(adrgCode) && !"null".equals(adrgCode) && !"未入组".equals(adrgCode) && !"未分组".equals(adrgCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   adrg.ADRG_CODE=:adrgCode and  1=1   ");
			map.put("adrgCode", adrgCode);
		} else if ("null".equals(adrgCode) || "未入组".equals(adrgCode) || "未分组".equals(adrgCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   adrg.ADRG_CODE is null and  1=1   ");
		}
		// ***DRG*****
		if (StringUtils.hasLength(drgCode) && !"null".equals(drgCode) && !"未入组".equals(drgCode) && !"未分组".equals(drgCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   drg.drg_code=:drgCode and  1=1   ");
			map.put("drgCode", drgCode);
		} else if ("null".equals(drgCode) || "未入组".equals(drgCode) || "未分组".equals(drgCode)) {
			sqlStr = sqlStr.replaceAll("1=1", "   drg.drg_code is null and  1=1   ");
		}
		// 特异病例和矫正指标替换,specHeade指定上一级（这些指标仅在科室指标象限分析和医保首页点进二级页面使用，暂时没有考虑医师钻取的情况）
		if ("hosp".equals(specHeade) && sqlStr.contains("4=4")) {

		} else if ("depGroup".equals(specHeade) && sqlStr.contains("4=4") && StringUtils.hasLength(depGroupCode)) {
			sqlStr = sqlStr.replace("4=4", "  depgroup.DEPGROUP_CODE=:specDepGroupCode and 4=4  ");
			map.put("specDepGroupCode", depGroupCode);
		} else if ("dep".equals(specHeade) && sqlStr.contains("4=4") && StringUtils.hasLength(depCode)) {
			sqlStr = sqlStr.replace("4=4", "  dep.DEP_CODE=:specDepCode and 4=4  ");
			map.put("specDepCode", depCode);
		} else if ("ward".equals(specHeade) && sqlStr.contains("4=4") && StringUtils.hasLength(wardCode)) {
			sqlStr = sqlStr.replace("4=4", "  ward.ward_code=:specWardCode and 4=4  ");
			map.put("specWardCode", wardCode);
		} else if ("mdc".equals(specHeade) && sqlStr.contains("4=4") && StringUtils.hasLength(mdcCode)) {
			sqlStr = sqlStr.replace("4=4", "   mdc.MDC_CODE=:specMdcCode and 4=4  ");
			map.put("specMdcCode", mdcCode);
		} else if ("adrg".equals(specHeade) && sqlStr.contains("4=4") && StringUtils.hasLength(adrgCode)) {
			sqlStr = sqlStr.replace("4=4", "  adrg.ADRG_CODE=:specAdrgCode and 4=4  ");
			map.put("specAdrgCode", adrgCode);
		}
		// ***医院编码*** && 有mr_baseinfo 表
		if (StringUtils.hasLength(hospCode) && sqlStr.toLowerCase().contains("mr_baseinfo")) {
			String[] hosps = hospCode.split(",");
			if (hosps.length > 1) {
				sqlStr = sqlStr.replaceAll("1=1", "   instr(:hospCode,a.p00010001)>0 and  1=1  ");
				sqlStr = sqlStr.replaceAll("'capScore'='capScore'", "  instr(:hospCode,a.p00010001)>0 and  'capScore'='capScore' ");// 科室安全得分
			} else {
				sqlStr = sqlStr.replaceAll("1=1", "   a.p00010001=:hospCode  and  1=1  ");
				sqlStr = sqlStr.replaceAll("'capScore'='capScore'", "   a.p00010001=:hospCode  and  'capScore'='capScore' ");// 科室安全得分
			}
			map.put("hospCode", hospCode);
		}
		if(StringUtils.hasLength(hospName) && "清华长庚".equals(hospName) && StringUtils.hasLength(roleName) && "科室".equals(roleName) ){
			sqlStr = sqlStr.replaceAll("1=1", "  confirmflag=1 and  1=1   ");
		}

		// 以下部分和monitorType没关系
		// ***多个科室*****
		if (StringUtils.hasLength(deps)) {
			sqlStr = setDepsSql(deps, sqlStr, "dep.dep_code");
		}

		// ***历史数据查询，关联分组信息表时添加上版本号的过滤*****
		if (isHistory != null && "1".equals(isHistory)) {
			sqlStr = sqlStr.replaceAll("on a.pmainindex=b.parid", "  on a.pmainindex=b.parid  and b.VER_CODE=:verCode  ");
			map.put("verCode", verCode);
		}
		/* 过滤医保病例 */
		if ("1".equals(pType) && sqlStr.contains("DRGs.t_medins")) {
			sqlStr = sqlStr.replaceAll("1=1", " d.parid is not null and  1=1 ");
		}
		// 添加医保指标中基金类型的过滤
		/*
		 * if (StringUtils.hasLength(pType) && "1".equals(pType) &&
		 * StringUtils.hasLength(hcType) && sqlStr.contains("DRGs.t_medins")) { sqlStr =
		 * sqlStr.replaceAll("1=1", "   instr(m.hi_type,:hcType) >0  and 1=1   ");
		 * map.put("hcType", hcType); }
		 */
		// 重点病组分析
		if (null != isKeyDisGroup && "1".equals(isKeyDisGroup)) {
			int offset = sqlStr.indexOf("left join drgs.t_drgs drg");
			StringBuilder strB = new StringBuilder(sqlStr);
			String str = "inner join drgs.t_keydisgroup kdg \n on kdg.drg_code = b.pardrg_code \n ";
			if (StringUtils.hasLength(index.getPardepCode())) {
				str += " and kdg.CONF_CODE = 'keyGroup_" + index.getUserCode() + "_" + index.getPardepCode() + "' ";
			} else {
				str += " and kdg.CONF_CODE = 'keyGroup_" + index.getUserCode() + "_Hosp' ";
			}
			strB.insert(offset, str);
			sqlStr = strB.toString();
			if (StringUtils.hasLength(groupType) && !"null".equals(groupType)) {
				sqlStr = sqlStr.replaceAll(" 1=1 ", " kdg.group_type=:groupType and  1=1 ");
				map.put("groupType", groupType);
			} else if ("null".equals(groupType)) {
				sqlStr = sqlStr.replaceAll(" 1=1 ", " kdg.group_type is null and  1=1 ");
			}
		}
		// 疑难病组分析
			if (null != isDifDisGroup && "1".equals(isDifDisGroup)) {
				String cfgCode = "DiffiConfig"+"-"+userAccount+"-"+hospCode;
				String difficultSql = " 1=1 and exists(select pu.drg_code from drgs.mr_puzzle_drg pu where pu.par_moudle_code='"+cfgCode+"' "
						+ "  and pu.drg_code=b.pardrg_code and (pu.del_type is null or pu.del_type='0')) ";
				if(null!=monitorType && "dep".equals(monitorType)){
					difficultSql = difficultSql+" and pardrg_code='"+drgCode+"'";
				}
				sqlStr = sqlStr.replaceAll("1=1", difficultSql);
			}
		// 付费病组
		if (null != isPayGroup && "1".equals(isPayGroup)) {
			sqlStr = sqlStr.replaceAll(" 1=1 ", " drg.pay_group = '1' and  1=1 ");
		} else if (null != isPayGroup && "0".equals(isPayGroup)) {
			sqlStr = sqlStr.replaceAll(" 1=1 ", " drg.pay_group = '0' and  1=1 ");
		}
		if ("CapacityScore".equals(index.getQuotaCode())) {
			sqlStr = replaceCapacityScore(sqlStr, index);
		}
		index.setSqlStr(sqlStr);
	}
	/**
	 * 
	 *  replaceMDC.  
	 *  @Description：替换MDC
	 *  @Author LiuHongjun
	 *  @param sqlStr
	 *  @param index
	 *  @return 
	 *  @Date:2017年6月26日上午6:57:51
	 */
	public static String replaceMDC(String sqlStr,IndexCal index){
		String mdcCode=index.getParmdcCode();
		if(StringUtils.hasLength(mdcCode) && !"null".equals(mdcCode) && !"未入组".equals(mdcCode) && !"未分组".equals(mdcCode)){
			sqlStr = sqlStr.replaceAll("-replace_t_mdc-", "   left join drgs.t_mdcgroup mdc on mdc.MDC_CODE=adrg.MDC_CODE and mdc.VER_CODE=adrg.VER_CODE   ");
		}else{
			sqlStr = sqlStr.replaceAll("-replace_t_mdc-", "");
		}
		return sqlStr;
	}
	/**
	 * 
	 *  replaceWard.  
	 *  @Description：替换病区
	 *  @Author LiuHongjun
	 *  @param sqlStr
	 *  @param index
	 *  @return 
	 *  @Date:2017年7月17日下午5:26:13
	 */
	public static String replaceWard(String sqlStr, IndexCal index) {
		String wardCode = index.getParwardCode();
		if ("ward".equals(index.getMonitorType())
				|| (StringUtils.hasLength(wardCode) && ("resident".equals(index.getMonitorType())
						|| "physician".equals(index.getMonitorType()) || "protomedicus".equals(index.getMonitorType())
						|| "clinic".equals(index.getMonitorType()) || "mdc".equals(index.getMonitorType())|| "drgs".equals(index.getMonitorType())|| "adrg".equals(index.getMonitorType())))) {
			sqlStr = sqlStr.replaceAll("-replace_t_ward-",
					"   left join drgs.t_ward ward on ipinfo.P00310001 =ward.ward_code    ");
		} else {
			sqlStr = sqlStr.replaceAll("-replace_t_ward-", "");
		}
		return sqlStr;
	}
	/**
	 * 
	 *  replaceDoctor.  
	 *  @Description：
	 *  @Author LiuHongjun
	 *  @param sqlStr
	 *  @param index
	 *  @return 
	 *  @Date:2017年7月17日下午6:44:45
	 */
	public static String replaceDoctor(String sqlStr,IndexCal index){
		if( "clinic".equals(index.getMonitorType())){
			sqlStr = sqlStr.replaceAll("-replace_t_doctor-", "   left join drgs.t_clinicgroup  clinic on ipinfo.P00601001 =clinic.group_code   ");
			sqlStr =replaceDoctorObj(sqlStr,"P00601001");
			// 根据医师类型替换不同的字段
			sqlStr = sqlStr.replaceAll("-groupCode-", " P00601001 ") ;
		}else if("protomedicus".equals(index.getMonitorType())){
			sqlStr = sqlStr.replaceAll("-replace_t_doctor-", "   left join drgs.t_clinicgroup  clinic on ipinfo.P00600201 =clinic.group_code   ");
			sqlStr =replaceDoctorObj(sqlStr,"P00600201");
			// 根据医师类型替换不同的字段
			sqlStr = sqlStr.replaceAll("-groupCode-", "P00600201") ;
		}else if("physician".equals(index.getMonitorType())){
			sqlStr = sqlStr.replaceAll("-replace_t_doctor-", "   left join drgs.t_clinicgroup  clinic on ipinfo.P00600301 =clinic.group_code   ");
			sqlStr =replaceDoctorObj(sqlStr,"P00600301");
			// 根据医师类型替换不同的字段
			sqlStr = sqlStr.replaceAll("-groupCode-", "   P00600301   ") ;
		}else if("resident".equals(index.getMonitorType())){
			sqlStr = sqlStr.replaceAll("-replace_t_doctor-", "   left join drgs.t_clinicgroup  clinic on ipinfo.P00600401 =clinic.group_code   ");
			sqlStr =replaceDoctorObj(sqlStr,"P00600401");
			// 根据医师类型替换不同的字段
			sqlStr = sqlStr.replaceAll("-groupCode-", "   P00600401   ") ;
		}else {
			sqlStr = sqlStr.replaceAll("-replace_t_doctor-", " ");
		}
		return sqlStr;
	}
	/**
	 * 
	 *  @desp  ：产能得分拼接
	 *  @Author： lhj
	 *  @param sqlStr
	 *  @param indexCal
	 *  @return
	 *  @Date  :2018年2月9日上午8:55:39
	 */
	private static String replaceCapacityScore(String sqlStr,IndexCal indexCal) {
		String monitorType=indexCal.getMonitorType();
		String setStr=GlobalData.sysConfig.get("DEP_LINE_LAYER");
		String set[]={"1","1","1","1"};
		set=setStr.split(",");
		//根据系统分层配置中的层级关系来获取上一级
		if("depGroup".equals(monitorType)){
			sqlStr=sqlStr.replace("-currentcode-", "depgroup.depgroup_code");
			sqlStr=sqlStr.replace("-monitorcode-", "'1'");
		}else if("dep".equals(monitorType)){
			sqlStr=sqlStr.replace("-currentcode-", "dep.dep_code");
			//上一级是科室组或全院
			if("1".equals(set[0])){
				sqlStr=sqlStr.replace("-monitorcode-", "depgroup.depgroup_code");
			}else{
				sqlStr=sqlStr.replace("-monitorcode-", "'1'");
			}
		}else if("ward".equals(monitorType)){
			sqlStr=sqlStr.replace("-currentcode-", "ward.ward_code");
			//上一级是科室或科室组或全院
			if("1".equals(set[1])){//科室
				sqlStr=sqlStr.replace("-monitorcode-", "dep.dep_code");
			}else if("1".equals(set[0])&&"0".equals(set[1])){//科室组
				sqlStr=sqlStr.replace("-monitorcode-", "depgroup.depgroup_code");
			}else if("0".equals(set[0])&&"0".equals(set[1])){//全院
				sqlStr=sqlStr.replace("-monitorcode-", "'1'");
			}
		}else if(monitorType.matches("(protomedicus)|(clinic)|(physician)|(resident)")){
			sqlStr=sqlStr.replace("-currentcode-", "clinic.group_code");
			//上一级是科室或病区
			if("1".equals(set[2])){//病区
				sqlStr=sqlStr.replace("-monitorcode-", "ward.ward_code");
			}else if("1".equals(set[1])&&"0".equals(set[2])){//科室
				sqlStr=sqlStr.replace("-monitorcode-", "dep.dep_code");
			}
		}
		return sqlStr;
	}
	/**
	 * 
	 *  replaceDoctorObj.  
	 *  @Description：替换医师代码
	 *  @Author LiuHongjun
	 *  @param sqlStr
	 *  @param  1=1基本过滤条件，2=2 是替换医师所在部门,3=3 只有departmentOfDoctor指标应用到，其他指标都不用,4=4是特异病例专用替换
	 *  @return 
	 *  @Date:2017年7月17日下午7:06:17
	 */
	public static String replaceDoctorObj(String sqlStr,String code){
		sqlStr = sqlStr.replaceAll("-obj-", "   clinic.group_code ccode   ");
		sqlStr = sqlStr.replaceAll("-obj1-", "   clinic.group_code ccode,clinic.group_name ddesc ");
		sqlStr = sqlStr.replaceAll("-grbyobj-", "  clinic.group_code   ");
		sqlStr = sqlStr.replaceAll("-grbyobj1-","  clinic.group_code,clinic.group_name  ");
		sqlStr = sqlStr.replaceAll("-obj2-", "  '1' ccode  ");
		sqlStr = sqlStr.replaceAll("-grbyobj2-", "'1'");
		//sqlStr = sqlStr.replaceAll("1=1", "  "+code+" is not null and  1=1   ");
		
		sqlStr = sqlStr.replaceAll("-baseobj1-", "clinic.group_code ccode,clinic.group_name ddesc,clinic.GROUP_ORDER drgorder");
		sqlStr = sqlStr.replaceAll("-grbybaseobj1-", "clinic.group_code ,clinic.group_name ,clinic.GROUP_ORDER");
		return sqlStr;
	}
	
	
	/**
	 * 
	 *  jointListAndMap.  
	 *  @Description：拼接list和map
	 *  @Author LiuHongjun
	 *  @param list
	 *  @param map
	 *  @return 
	 *  @Date:2017年5月24日上午8:53:48
	 */
	public static List<Map<String, Object>> jointListAndMap(List<Map<String, Object>> list, Map<String, Object> map){
    	int i=0;
    	int iMax=list.size();
		for(i=0; i<iMax; i++){
    		Map<String, Object> mapo = list.get(i);
    		for(String dataKey : map.keySet())   {    
				mapo.put(dataKey+"cc", map.get(dataKey));
			} 
    	}
    	return list;
    }

	/**
	 * 
	 *  replacementQuotaCode.  
	 *  @Description：	以下替换指标为特殊计算院内均值的指标，根据前台传过来的指标计算代码来替换为真是的指标代码，
						特殊的院内均值计算时MonitorType传递不变，如科室的drg组数院内均值comparetype传
						hosp，monitortype传dep，其他的指标MonitorType统一置为hosp
	 *  @Author LiuHongjun
	 *  @param index 
	 *  @Date:2017年6月9日上午9:34:54
	 */
	public static void replacementQuotaCode(IndexCal index){
		/*以下替换指标为特殊计算院内均值的指标，根据前台传过来的指标计算代码来替换为真是的指标代码，
		特殊的院内均值计算时MonitorType传递不变，如科室的drg组数院内均值comparetype传
		hosp，monitortype传dep，其他的指标MonitorType统一置为hosp*/
		
		String quotaCode=index.getReplaceQuotaCode();
		//保持院内均值指标代码不变
		Map<String,Object> quotaMap=new HashMap<>();
		
		if("DRGCount".equals(quotaCode)){
			quotaMap.put("AvgDRGCount", "DRGCount");
			quotaCode="AvgDRGCount";
		}else if("TotalFee".equals(quotaCode)){
			//总费用（全院总费用/对象个数）
			quotaMap.put("AvgTotalFee", "TotalFee");
			quotaCode="AvgTotalFee";
		}else if("InCaseCnt".equals(quotaCode)){
			//入组病例数（全院入组病例数据/对象个数）
			quotaMap.put("AvgInCaseCnt", "InCaseCnt");
			quotaCode="AvgInCaseCnt";
		}else if("TotalCaseCnt".equals(quotaCode)){
			//出院病例数（全院出院病例数据/对象个数）
			quotaMap.put("AvgTotalCaseCnt", "TotalCaseCnt");
			quotaCode="AvgTotalCaseCnt";
		}else if("DeadCaseCnt".equals(quotaCode)){
			//死亡人数（全院死亡病例数据/对象个数）
			quotaMap.put("AvgDeadCaseCnt", "DeadCaseCnt");
			quotaCode="AvgDeadCaseCnt";
		}else if("DrugFee".equals(quotaCode)){
			//药品费用（全院药品费用/对象个数）
			quotaMap.put("AvgDrugFee", "DrugFee");
		}else if("MaterialFee".equals(quotaCode)){
			//材料费用（全院材料费用/对象个数）
			quotaMap.put("AvgMaterialFee", "MaterialFee");
		}else if("TotalWeight".equals(quotaCode)){
			//总权重（全院宗权重/对象个数）
			quotaMap.put("AvgTotalWeight", "TotalWeight");
			quotaCode="AvgTotalWeight";
		}else{
			quotaMap.put(quotaCode,quotaCode);
			index.setMonitorType("hosp");
		}
		index.setReplaceQuotaCode(quotaCode);
		index.setQuotaMap(quotaMap);
	}
	
	/**
	 * 
	 *  equals.  
	 *  @Description：判断时间是否为同月
	 *  @Author LiuHongjun
	 *  @param dateFrom
	 *  @param dateTo
	 *  @return 
	 * @throws ParseException 
	 *  @Date:2017年7月8日下午9:21:36
	 */
	  public static boolean equalsDate(String dateFrom, String dateTo)  {
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	        Calendar calendarFrom = Calendar.getInstance();
	        Calendar calendarTo = Calendar.getInstance();
	        try {
				calendarFrom.setTime(sdf.parse(dateFrom));
		        calendarTo.setTime(sdf.parse(dateTo));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	        return calendarFrom.get(Calendar.YEAR) == calendarTo.get(Calendar.YEAR) && calendarFrom.get(Calendar.MONTH) == calendarTo.get(Calendar.MONTH);   
	    } 
	  
	 /**
	  * 
	  *  replaceSqlByMonitorType.  
	  *  @Description：超标病例sql替换 
	  *  @Author LiuHongjun
	  *  @param compareType比较类型
	  *  @param quotaCode指标代码
	  *  @param pType病例类型
	  *  @param sqlStr
	  *  @return 
	  *  @Date:2017年7月11日下午6:30:45
	  */
	public static String  replaceExcess(String compareType,String quotaCode,String pType,String sqlStr){
		
			//超标病例问题
			if("year".equals(compareType) ||"month".equals(compareType)){
				if(("ExcessCnt_F".equals(quotaCode)||"ExcessRatio_F".equals(quotaCode)) && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", "   SELECT std.as_drg_code pardrg_code  , std.as_avg_fee  mAvgFee \n"
							               + "  FROM drgs.t_annualstd std where std.AS_ID=:stdId    \n");
					
				}else if(("ExcessCnt_T".equals(quotaCode)||"ExcessRatio_T".equals(quotaCode))&& sqlStr.contains("-replace_Excess_T-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-", "   SELECT std.as_drg_code pardrg_code  , std.as_avg_days  mAvgDays \n"
							                 + " FROM drgs.t_annualstd std where std.AS_ID=:stdId     \n");	
				}else if(("ExcessCnt_TF".equals(quotaCode)||"ExcessRatio_TF".equals(quotaCode)) && sqlStr.contains("-replace_Excess_T-") && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", "   SELECT std.as_drg_code pardrg_code  , std.as_avg_days  mAvgDays \n"
							                 + " FROM drgs.t_annualstd std where std.AS_ID=:stdId     \n");	
					
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-", "   SELECT std.as_drg_code pardrg_code  , std.as_avg_fee  mAvgFee\n"
							                 + " FROM drgs.t_annualstd std where std.AS_ID=:stdId     \n");
				}
				
			}else if("manage".equals(compareType)){
				String rep_cnt_f="   select pardrg_code, manage_benchmark mAvgFee \n"
						+ "from drgs.t_quotamanage  \n "
						+ "where pardep_code is null  \n "
						+ "and pardepgroup_code is null  \n"
						+ "and parquota_code='AvgFee'  \n"
						+ "and par_ms_code=:ms_code  \n"
				        + "and manage_year =:manageYear  \n";
				String rep_cnt_t=" select pardrg_code, manage_benchmark mAvgDays   \n"			
						+ "from drgs.t_quotamanage  \n "
						+ "where pardep_code is null   \n"
						+ "and pardepgroup_code is null \n "
						+ "and parquota_code='AvgDays'  "
						+ "and par_ms_code=:ms_code  \n"
						+ "and manage_year =:manageYear    ";
				if(("ExcessCnt_F".equals(quotaCode)||"ExcessRatio_F".equals(quotaCode)) && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-",rep_cnt_f);	
				}else if(("ExcessCnt_T".equals(quotaCode)||"ExcessRatio_T".equals(quotaCode)) && sqlStr.contains("-replace_Excess_T-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-", rep_cnt_t);
				}else if(("ExcessCnt_TF".equals(quotaCode)||"ExcessRatio_TF".equals(quotaCode))&& sqlStr.contains("-replace_Excess_T-") && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-",rep_cnt_f);	
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-",rep_cnt_t);
				}
				
			}else if("std".equals(compareType)){
				String rep_cnt = "select std.as_drg_code PARDRG_CODE,std.as_avg_fee mAvgFee,std.as_avg_days mAvgDays from drgs.t_annualstd std"+
							" where std.as_id = :stdId ";
				if(("ExcessCnt_F".equals(quotaCode)||"ExcessRatio_F".equals(quotaCode)) && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", rep_cnt);	
				}else if(("ExcessCnt_T".equals(quotaCode)||"ExcessRatio_T".equals(quotaCode)) && sqlStr.contains("-replace_Excess_T-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-", rep_cnt);
				}else if(("ExcessCnt_TF".equals(quotaCode)||"ExcessRatio_TF".equals(quotaCode))&& sqlStr.contains("-replace_Excess_T-") && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", rep_cnt);	
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-",rep_cnt);
				}
			}else if("hosp".equals(compareType)){
				String rep_cnt_t="   SELECT b.pardrg_code, avg(ipinfo.P00320000) mAvgDays \n"
						+ "FROM  DRGs.Mr_Baseinfo a  \n"
						+ "left join drgs.mr_ipinfo ipinfo    on a.pmainindex = ipinfo.pmainindex   \n"
						+ " left join DRGs.t_patientdrg b     on a.pmainindex=b.parid \n";
						if(pType.equals("1")){
						  rep_cnt_t +="  left join DRGs.t_medins d on d.parid=a.pmainindex   \n";	
						}
						rep_cnt_t += "  where b.pardrg_code is not null \n"
						+ "and to_char(ipinfo.p00290000,'yyyy-mm-dd') between  :dateFrom  and :dateTo \n"
						+ "group by b.pardrg_code \n";
				String rep_cnt_f="   SELECT b.pardrg_code, avg(ipinfo.P00800000) mAvgFee \n"
						+ "FROM  DRGs.Mr_Baseinfo a  \n"
						+ "left join drgs.mr_ipinfo ipinfo    on a.pmainindex = ipinfo.pmainindex   \n"
						+ " left join DRGs.t_patientdrg b     on a.pmainindex=b.parid \n";
						if("1".equals(pType)){
						  rep_cnt_f +="  left join DRGs.t_medins d on d.parid=a.pmainindex \n";	
						}
						rep_cnt_f += "  where b.pardrg_code is not null \n"
						+ "and to_char(ipinfo.p00290000,'yyyy-mm-dd') between  :dateFrom  and :dateTo \n"
						+ "group by b.pardrg_code \n";
				if(("ExcessCnt_F".equals(quotaCode)||"ExcessRatio_F".equals(quotaCode)) && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", rep_cnt_f);	
					
				}else if(("ExcessCnt_T".equals(quotaCode)||"ExcessRatio_T".equals(quotaCode)) && sqlStr.contains("-replace_Excess_T-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-", rep_cnt_t);
					if(sqlStr.contains("and manageAvgDays.n=1")){
						sqlStr.replaceAll("and manageAvgDays.n=1","");
					}
				}else if(("ExcessCnt_TF".equals(quotaCode)||"ExcessRatio_TF".equals(quotaCode)) && sqlStr.contains("-replace_Excess_T-") && sqlStr.contains("-replace_Excess_F-")){
					sqlStr = sqlStr.replaceAll("-replace_Excess_F-", rep_cnt_f);	
					sqlStr = sqlStr.replaceAll("-replace_Excess_T-",rep_cnt_t);
					
				}
			}
			return sqlStr;
		}
	
	/**
	 * 
	 *  notInReasonPharse.  
	 *  @Description：解析未入组原因结果，返回未入组原因代码
	 *  @Author WENYI
	 *  @param pMainIndex
	 *  @param notInReasonJson
	 *  @return 
	 *  @Date:2017年8月25日上午10:58:53
	 */
	public static String notInReasonPharse(String pMainIndex,String notInReasonJson){
		ObjectMapper objectMapper = new ObjectMapper();
		String notInReason="o_other";
		try {
			Map<String,Object> notInReasonMap=objectMapper.readValue(notInReasonJson, Map.class);
			if(!(boolean)notInReasonMap.get("error")){
				notInReason=notInReasonMap.get("notInGroupReason").toString();
			}
			return notInReason;
		}catch (Exception e) {
			e.printStackTrace();
			return notInReason;
		}
	}
/**
 * 
 *  copyProperties.  
 *  @Description：系统类属性的深度复制
 *  @Author LiuHongjun
 *  @param qdto 新定义的类对象
 *  @param dto  含有参数的类对象
 *  @Date:2017年9月26日上午8:48:32
 */
public static void copyProperties(IndexCalDTO qdto,IndexCalDTO dto)  {
	try {
		PropertyUtils.copyProperties(qdto, dto);
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		e.printStackTrace();
	} catch (NoSuchMethodException e) {
		e.printStackTrace();
	}
}
/**
 *  copyProperties.  
 *  @Description：对象深度复制
 *  @Author LiuHongjun
 *  @param obj 所有对象
 *  @return 
 *  @Date:2017年10月18日上午9:18:41
 */
public static Object copyPropertiesObj(Object obj) {  
    try {// 将对象写到流里  
        ByteArrayOutputStream bo = new ByteArrayOutputStream();  
        ObjectOutputStream oo = new ObjectOutputStream(bo);  
        oo.writeObject(obj);// 从流里读出来  
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());  
        ObjectInputStream oi = new ObjectInputStream(bi);  
        return (oi.readObject());  
    } catch (Exception e) {  
        return null;  
    }  
}
/**
 * 
 *  setElementValue.  
 *  @Description：java反射机制
 *  @Author LiuHongjun
 *  @param entiy 实体类
 *  @param dataTypeCode 数据库定义的字段数据类型
 *  @param dataScale 小数点位数
 *  @param fieldCode 数据库字段名称
 *  @param nodeTextVal xml节点值
 *  @param dataFormatCode 日期格式化 d（yyyy-MM-dd），dt(yyyy-MM-dd HH:mm:ss)
 *  @param filedMap 字段名与属性名映射
 *  @throws Exception 
 *  @Date:2017年10月10日下午9:11:50
 */
public static void setElementValue(Object entiy, String  dataTypeCode, String  dataScale, String fieldCode,String nodeTextVal,String dataFormatCode,Map<String,Object> filedMap) throws Exception {
	String oldFileCode=fieldCode;
	try {
		if(filedMap!=null) {
		    fieldCode=filedMap.get(fieldCode)==null?"":filedMap.get(fieldCode).toString();		
			if(!"".equals(fieldCode)) {
			     fieldCode = fieldCode.substring(0, 1).toUpperCase() + fieldCode.substring(1);
			 }else {
				 fieldCode = oldFileCode.substring(0, 1).toUpperCase() + oldFileCode.substring(1).toLowerCase();
			 }
		}else {
			 fieldCode = oldFileCode.substring(0, 1).toUpperCase() + oldFileCode.substring(1).toLowerCase();
		}
		
		/**
	     * 对不同的数据类型调用set方法 
	     */
	    if (StringUtils.hasLength(dataScale) && "number".equals(dataTypeCode) && Integer.parseInt(dataScale) == 0 && nodeTextVal.matches("^(\\-|\\+)?(\\d+)$") ) {//整数
	      //反射调用Set方法
	    	entiy.getClass().getMethod("set"+fieldCode, new Class[]{Integer.class}).invoke(entiy, new Object[]{Integer.parseInt(nodeTextVal)});
	    }else if (StringUtils.hasLength(dataScale) && "number".equals(dataTypeCode) && Integer.parseInt(dataScale) > 0 && nodeTextVal.matches("^(\\-|\\+)?(\\d+\\.\\d+|\\d+|\\.\\d+)$") ) {//小数
	        //反射调用Set方法
	    	entiy.getClass().getMethod("set"+fieldCode, new Class[]{Double.class}).invoke(entiy, new Object[]{Double.parseDouble(nodeTextVal)});
	    }else if ("string".equals(dataTypeCode)) {
	        //反射调用Set方法
	    	entiy.getClass().getMethod("set"+fieldCode, new Class[]{String.class}).invoke(entiy, new Object[]{nodeTextVal});
	    }else if (StringUtils.hasLength(dataFormatCode) && "date".equals(dataTypeCode)) {
	        //反射调用Set方法
	        entiy.getClass().getMethod("set"+fieldCode, new Class[]{Date.class}).invoke(entiy, new Object[]{DrgsIndex.parseDateStr(nodeTextVal)});
	    }
  }catch(Exception e) {
	  logger.error(e.getMessage());
	  e.printStackTrace();
   }
  }
/**
 *  @desp  ：java反射机制
 *  @Author： lhj
 *  @param entiy 实体类
 *  @param fieldCode 字典名字
 *  @param fieldValue 字段对应的值
 *  @param dataFormat 格式化
 *  @param filedMap 实体属性和数据库字段对应关系
 *  @throws Exception
 *  @Date  :2018年2月10日下午8:41:12
 */
public static String setElementValueFileUpload(Object entiy, String fieldCode, String fieldValue, String dataFormat,Map<String, Object> filedMap) throws Exception {
	String errInfo = "";
	String oldFileCode = fieldCode;
	try {
		if (filedMap != null) {
			fieldCode = filedMap.get(fieldCode) == null ? "" : filedMap.get(fieldCode).toString();
			if (!"".equals(fieldCode)) {
				fieldCode = fieldCode.substring(0, 1).toUpperCase() + fieldCode.substring(1);
			} else {
				fieldCode = oldFileCode.substring(0, 1).toUpperCase() + oldFileCode.substring(1).toLowerCase();
			}
		} else {
			fieldCode = oldFileCode.substring(0, 1).toUpperCase() + oldFileCode.substring(1).toLowerCase();
		}
		fieldCode = replaceUnderlineAndfirstToUpper(fieldCode, "_", "");
	
		/**
		 * 对不同的数据类型调用set方法
		 */
		if ("Integer".equals(dataFormat) && fieldValue.matches("^(\\-|\\+)?(\\d+\\.\\d+|\\d+|\\.\\d+)$")) {// 整数
			// 反射调用Set方法
			entiy.getClass().getMethod("set" + fieldCode, new Class[] { Integer.class }).invoke(entiy, new Object[] { Double.valueOf(fieldValue).intValue() });
		} else if ("Double".equals(dataFormat) && fieldValue.matches("^(\\-|\\+)?(\\d+\\.\\d+|\\d+|\\.\\d+)$")) {// 小数
			// 反射调用Set方法
			entiy.getClass().getMethod("set" + fieldCode, new Class[] { Double.class }).invoke(entiy, new Object[] { Double.parseDouble(fieldValue) });
		} else if ("String".equals(dataFormat)&&StringUtils.hasLength(fieldValue)) {
			// 反射调用Set方法
			entiy.getClass().getMethod("set" + fieldCode, new Class[] { String.class }).invoke(entiy, new Object[] { fieldValue });
		} else if ("Date".equals(dataFormat)) {
			// 反射调用Set方法
			entiy.getClass().getMethod("set" + fieldCode, new Class[] { Date.class }).invoke(entiy, new Object[] { DrgsIndex.parseDateStr(fieldValue) });
		}
	}catch(Exception e) {
		errInfo = e.getMessage();
	}
	return errInfo;
}

/**
 * 首字母大写
 * 
 * @param srcStr
 * @return
 */
public static String firstCharacterToUpper(String srcStr) {
	return srcStr.substring(0, 1).toUpperCase() + srcStr.substring(1);
}

/**
 * 替换字符串并让它的下一个字母为大写
 * 
 * @param srcStr
 * @param org
 * @param ob
 * @return
 */
public static String replaceUnderlineAndfirstToUpper(String srcStr, String org, String ob) {
	String newString = "";
	int first = 0;
	while (srcStr.indexOf(org) != -1) {
		first = srcStr.indexOf(org);
		if (first != srcStr.length()) {
			newString = newString + srcStr.substring(0, first) + ob;
			srcStr = srcStr.substring(first + org.length(), srcStr.length());
			if(!StringUtils.hasLength(srcStr)) break;
			srcStr = firstCharacterToUpper(srcStr);
		}
	}
	newString = newString + srcStr;
	return newString;
}

/**
 *  @desp  ：拼接两个map
 *  @Author： lhj
 *  @param resultMap 本期值
 *  @param partMap 比较值
 *  @Date  :2017年12月15日下午3:48:40
 */
public static void mergeResultMap(Map<String, Object> resultMap, Map<String, Object> partMap) {
	try {
		if(partMap!=null && resultMap!=null) {
			for (Entry<String, Object> entry : partMap.entrySet()) {
				String key = entry.getKey();
				if (resultMap.containsKey(key)) {
					resultMap.put(key+"cc", entry.getValue()) ;
				} /*else {
					resultMap.putAll(partMap);
				}
*/			}	
		}
	}catch (Exception e) {
		e.printStackTrace();
	}
}

/**
 *  @desp  ：比较值为全院均值的时候拼接
 *  @Author： lhj
 *  @param resultMap
 *  @param partMap
 *  @Date  :2017年12月18日上午11:01:36
 */
public static void mergeAvgHospResultMap(Map<String, Object> resultMap, Map<String, Object> partMap) {
	try {
		Map<String, Object> map= (Map<String, Object>) DrgsIndex.copyPropertiesObj(resultMap);
		if(partMap!=null && resultMap!=null) {
			for (Entry<String, Object> entry : map.entrySet()) {
				String key = entry.getKey();
				resultMap.put(key+"cc", partMap.get(key)) ;	
			}	
		}
	}catch (Exception e) {
		e.printStackTrace();
	}
}
	/**
	 * 
	 *  parseDateStr.  
	 *  @Description：将日期字符串转为日期
	 *  @Author mazhaoyan
	 *  @param date
	 *  @return 
	 * @throws ParseException 
	 *  @Date:2018年1月15日下午5:21:22
	 */
	public static Date parseDateStr(String dateStr) throws Exception {
		Date date = null;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//日期格式
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");//日期格式
		if(dateStr.matches("\\d+-\\d+-\\d+\\s+\\d+:\\d+:\\d+"))
		{
			date = sdf1.parse(dateStr);
		}
		else if(dateStr.matches("\\d+-\\d+-\\d+\\s+\\d+:\\d+"))
		{
			dateStr = dateStr+":00";
			date = sdf1.parse(dateStr);
		}
		else if(dateStr.matches("\\d+-\\d+-\\d+"))
		{
			dateStr = dateStr+" 00:00:00";
			date = sdf1.parse(dateStr);
		}
		else if(dateStr.matches("\\d+/\\d+/\\d+\\s+\\d+:\\d+:\\d+"))
		{
			date = sdf2.parse(dateStr);
		}
		else if(dateStr.matches("\\d+/\\d+/\\d+\\s+\\d+:\\d+"))
		{
			dateStr = dateStr+":00";
			date = sdf2.parse(dateStr);
		}
		else if(dateStr.matches("\\d+/\\d+/\\d+"))
		{
			dateStr = dateStr+" 00:00:00";
			date = sdf2.parse(dateStr);
		}
		else if(dateStr.matches("\\d+")&&dateStr.length()==14)
		{
			date = sdf3.parse(dateStr);
		}
		else if(dateStr.matches("\\d+")&&dateStr.length()==12)
		{
			dateStr = dateStr+"00";
			date = sdf3.parse(dateStr);
		}
		else if(dateStr.matches("\\d+")&&dateStr.length()==8)
		{
			dateStr = dateStr+" 00:00:00";
			date = sdf3.parse(dateStr);
		}
		return date;
	}
	//判断该对象是否: 返回ture表示所有属性为null  返回false表示不是所有属性都是null
    public static boolean isAllFieldNull(Object obj) throws Exception{
        Class stuCla = (Class) obj.getClass();// 得到类对象
        Field[] fs = stuCla.getDeclaredFields();//得到属性集合
        boolean flag = true;
        for (Field f : fs) {//遍历属性
        	if(!"serialVersionUID".equals(f.getName()))
        	{
        		f.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
                Object val = f.get(obj);// 得到此属性的值
                if(val!=null) {//只要有1个属性不为空,那么就不是所有的属性值都为空
                    flag = false;
                    break;
                }
        	}
        }
        return flag;
    }
    
    /**
     *  @desp  ：获取角色名称转码后
     *  @Author： lhj
     *  @return
     *  @Date  :2018年2月26日下午12:57:11
     */
    
    public static String getRoleCode(){
    	String code=CurrentUser.getRoleName();
    	if(code==null ) {//接口走公共方法
       	 code="医政";
    	}
    	if(!"暂未分配角色".equals(code)){
    		code=StringUtils.stringToAscii(code);
    		code=code.replaceAll(",", "");
    	}
    	return code;
    }
	
	public static SecurityAccessFacade getSecurityAccessFacade() {
		if (securityAccessFacade == null) {
			securityAccessFacade = InstanceFactory.getInstance(SecurityAccessFacade.class);
		}
		return securityAccessFacade;
	}
	/**
	 *  @desp  ：
	 *  @Author： liuhongjun
	 *  @param deps
	 *  @param sqlStr
	 *  @return
	 *  @Date  :2018年3月9日下午5:29:10
	 */
    public static String setDepsSql(String deps,String sqlStr,String table){
		deps="'"+deps+"'";
		deps=deps.replaceAll(",", "','");
		sqlStr = sqlStr.replaceAll(" 1=1 ", " "+table+" in("+deps+") and  1=1 ");
		return sqlStr;
    }


	/**
	 * 替换sql中的参数，主要用于测试
	 * @param sql
	 * @param obj 参数对象
	 */
	public static String repplaceParameterInSQL(String sql,Object obj) {
		if(obj instanceof Map) { // 参数是map
			// SQL查询参数赋值
			Iterator<Entry<String, Object>> ite = ((Map)obj).entrySet().iterator() ;
			while(ite.hasNext()) {
				//entry.getValue()==null?"null":entry.getValue().toString()
				Entry<String, Object> entry = ite.next() ;
				// 字段值替换-sql参数替换
				if(entry.getValue() instanceof String || entry.getValue() instanceof Character) {
					sql = sql.replace(":"+entry.getKey() , "'"+(entry.getValue()==null?"null":entry.getValue().toString())+"'") ;
				} else {
					sql = sql.replace(":"+entry.getKey() , entry.getValue()==null?"null":entry.getValue().toString()) ;
				}
			}
		} else if(obj instanceof List) { // 参数是list
			for(Object listo : (List)obj) {
				if(listo instanceof String || listo instanceof Character) {
					sql = sql.replaceFirst("\\?", "'"+(listo==null?"null":listo.toString())+"'") ;
				} else {
					sql = sql.replaceFirst("\\?", listo==null?"null":listo.toString().toString()) ;
				}
			}
		} else if(obj instanceof Object[]) { // 参数是 Object
			Object[] oa = (Object[])obj ;
			for(int i=0 ; i<oa.length; i++) {
				if(oa[i] instanceof String || oa[i] instanceof Character) {
					sql = sql.replaceFirst("\\?", "'"+(oa[i]==null?"null":oa[i].toString())+"'") ;
				} else {
					sql = sql.replaceFirst("\\?", oa[i]==null?"null":oa[i].toString()) ;
				}
			}
		} else { // 普通的实体
			for (Field field : obj.getClass().getDeclaredFields()) {
				field.setAccessible(true);
				try {
					if(field.get(obj) instanceof String || field.get(obj) instanceof Character) {
						sql = sql.replace(":"+field.getName() , "'"+(field.get(obj)==null?"null":field.get(obj).toString())+"'") ;
					} else {
						sql = sql.replace(":"+field.getName() , field.get(obj)==null?"null":field.get(obj).toString()) ;
					}
				} catch (IllegalArgumentException | IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
		return sql ;
	}

}
